package MULE.Model.Panel;

import javax.swing.*;

import MULE.Model.Logic.TitleLogic;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

/**
 * Panel for the title screen
 * 
 * @author Aditya Sehgal
 * @version 1.7
 */
public class TitlePanel extends JPanel {

	private ImageIcon mule;
	private JButton start;
	private JButton loadGame;
	private JLabel text, image;
	private Timer time;
	private int x;

	/**
	 * Instantiates a new title panel. Initializes all data members.
	 */
	public TitlePanel() {
		// Format panel.
		this.setLayout(new GridBagLayout());
		this.setBackground(Color.YELLOW);

		// Create panel components.
		mule = new ImageIcon("mule.png");
		image = new JLabel(mule);
		image.setBackground(Color.YELLOW);

		text = new JLabel("M.U.L.E.");
		text.setFont(new Font("Princetown LET", Font.BOLD, 72));
		time = new Timer(500, new TitleChangeListener());
		x = 0;
		start = new JButton("NEW GAME");
		start.setActionCommand(TitleLogic.ActionCommand.NEW_GAME.toString());
		loadGame = new JButton("LOAD GAME");
		loadGame.setActionCommand(TitleLogic.ActionCommand.LOAD_GAME.toString());
		// Add panel components.
		JPanel centerPanel = new JPanel(new BorderLayout());
		centerPanel.setBackground(Color.YELLOW);
		centerPanel.add(text, BorderLayout.PAGE_START);
		centerPanel.add(loadGame, BorderLayout.LINE_END);
		centerPanel.add(start, BorderLayout.LINE_START);
		this.add(centerPanel, new GridBagConstraints());

		// Start animation timer.
		time.start();
	}

	/**
	 * Sets the panel's logic module responsible for handling user input.
	 * 
	 * @param listener
	 *            The module which responds to user input.
	 */
	public void addStartListener(ActionListener listener) {
		start.addActionListener(listener);
	}

	/**
	 * Sets the panel's logic module responsible for handling user input on load
	 * button.
	 * 
	 * @param listener
	 *            The module which responds to user input.
	 */
	public void addLoadListener(ActionListener listener) {
		loadGame.addActionListener(listener);
	}

	/**
	 * JPanel's overridden paint method. Draws the mule on the panel.
	 */
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		mule.paintIcon(this, g, x, 150);
	}

	/**
	 * Listens to the timer. Changes the title's text color when fired.
	 */
	private class TitleChangeListener implements ActionListener {

		private Random random;

		/**
		 * Initialize the title color change listener.
		 */
		public TitleChangeListener() {
			random = new Random();
		}

		/**
		 * The listener's event handler method.
		 * 
		 * @param e
		 *            The event which invoked the listener.
		 */
		public void actionPerformed(ActionEvent e) {
			// Set title text to new random color.
			text.setForeground(new Color(random.nextInt(256), random
					.nextInt(256), random.nextInt(256)));
			repaint();
		}
	}
}